package com.syezon.wifikey.splash;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.WindowManager;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.syezon.wifikey.BuildConfig;
import com.syezon.wifikey.R;
import com.syezon.wifikey.ad.ConfigService;
import com.syezon.wifikey.ad.config.ConfigNewAdObserver;
import com.syezon.wifikey.base.BaseActivity;
import com.syezon.wifikey.config.AppConfig;
import com.syezon.wifikey.config.DeviceConfig;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;
import com.syezon.wifikey.home.MainActivity;
import com.syezon.wifikey.setting.GradeConfig;
import com.syezon.wifikey.splash.config.FrontAdConfig;
import com.syezon.wifikey.splash.config.SplashConfig;
import com.syezon.wifikey.splash.gdt.GdtNewSplashFragment;
import com.syezon.wifikey.splash.gdt.GdtSplashFragment;
import com.syezon.wifikey.splash.self.SelfNewAdSplashFragment;
import com.syezon.wifikey.splash.self.SelfSplashFragment;
import com.syezon.wifikey.splash.tt.TTNewSplashFragment;
import com.syezon.wifikey.splash.tt.TTSplashFragment;


import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public class SplashActivity extends BaseActivity implements SplashCallBack, ConfigNewAdObserver, SplashNewCallBack {

    private Handler mHandler = new Handler();
    private boolean isGoMain;

    private long mFetchSplashADTime;
    private static final long MAX_SPLASH_LOAD_TIME = 4000;
    private int retryCount;
    private List<String> mSplashAdOrderList = new ArrayList<>();
    private Runnable mGoMainTask = new Runnable() {
        @Override
        public void run() {
            LogUtils.eTag("splash", "goMain");
            goMain();
        }
    };

    private Runnable loadAdTask = new Runnable() {
        @Override
        public void run() {
            LogUtils.eTag("splash", "load ad ");
            AdInfo adInfo = SplashConfig.getNextAdSource();
            loadSplashAd(adInfo);
        }
    };

    private void loadSplashAd(AdInfo adInfo) {
        if (!FrontAdConfig.canShowAd()) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("loadSplashAd    不显示广告");
            }
            long alreadyDelayMills = System.currentTimeMillis() - mFetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
            long shouldDelayMills = alreadyDelayMills > MAX_SPLASH_LOAD_TIME ? 0 : MAX_SPLASH_LOAD_TIME
                    - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
            // 计算出还需要延时多久
            mHandler.postDelayed(mGoMainTask, shouldDelayMills);
        } else if (adInfo == null) {
            LogUtils.e("loadSplashAd  没有广告");
            /**
             * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
             * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
             * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
             **/
            long alreadyDelayMills = System.currentTimeMillis() - mFetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
            long shouldDelayMills = alreadyDelayMills > MAX_SPLASH_LOAD_TIME ? 0 : MAX_SPLASH_LOAD_TIME
                    - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
            // 计算出还需要延时多久
            mHandler.postDelayed(mGoMainTask, shouldDelayMills);
        } else if (AdInfo.AD_TYPE_GUANG_DIAN_TONG == adInfo.getType()) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("loadSplashAd  广点通");
            }
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, GdtNewSplashFragment.newInstance(adInfo))
                    .commitAllowingStateLoss();
        } else if (AdInfo.AD_TYPE_CHUAN_SHAN_JIA == adInfo.getType()) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("loadSplashAd  穿山甲");
            }
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, TTNewSplashFragment.newInstance(adInfo))
                    .commitAllowingStateLoss();
        } else if (AdInfo.AD_TYPE_APK == adInfo.getType() || AdInfo.AD_TYPE_WEB == adInfo.getType() || AdInfo.AD_TYPE_DEEPLINK == adInfo.getType()) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("loadSplashAd  自己的广告页显示");
            }
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, SelfNewAdSplashFragment.newInstance(adInfo))
                    .commitAllowingStateLoss();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.app_splash_activity);
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.app_splash_activity;
    }

    @Override
    protected void initViewsAndEvents() {
        ConfigService.getInstance().getConfig();
        //初始化设备及APP信息
        DeviceConfig.getDeviceConfig(this);
        ConfigService.getInstance().registerNewAdObserver(this);


        //初始化配置信息
//        ChannelConfig.initChannelConfig(this.getApplicationContext());
        boolean agree = AppConfig.isAgree();
        if (agree) {
            requestPermission();
        } else {
            AgreementDialog.showAgreement(this, new AgreementDialog.AgreementCallBack() {
                @Override
                public void onAgree() {
                    AppConfig.saveAgreement(true);
                    GradeConfig.saveFirstOpenAppTimeStamp();
                    requestPermission();
                }

                @Override
                public void onDelay() {
                    finish();
                }
            });
        }
    }

    private void requestPermission() {
        TTAdManagerHolder.init(this);
        PermissionUtils.permission(PermissionConstants.PHONE, PermissionConstants.STORAGE, PermissionConstants.LOCATION)
                .callback(new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        next();
                    }

                    @Override
                    public void onDenied() {
                        next();
                    }
                })
                .request();
    }

    private void next() {
        //UnlockViewModel.getInstance();
        //ChargeNotifyViewModel.getInstance();
        AppConfig.getAppConfig(this);
        mHandler.postDelayed(mGoMainTask, MAX_SPLASH_LOAD_TIME);
        String splashAdSource = SplashConfig.getSplashAdSource();
        mSplashAdOrderList = SplashConfig.getSplashAdOrderList();

        mFetchSplashADTime = System.currentTimeMillis();
        boolean granted = PermissionUtils.isGranted(Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        LogUtils.e("        next");
        mHandler.postDelayed(loadAdTask, 500);
    }

    private void loadSplashAd(String splashAdCode) {
        if (SplashConfig.SPLASH_AD_SOURCE_GDT.equals(splashAdCode)) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, GdtSplashFragment.newInstance(GDTConfig.SplashPosID))
                    .commitAllowingStateLoss();
        } else if (SplashConfig.SPLASH_AD_SOURCE_TT.equals(splashAdCode)) {
//            TTAdManagerHolder.get().requestPermissionIfNecessary(this);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, TTSplashFragment.newInstance())
                    .commitAllowingStateLoss();
        } else if (SplashConfig.SPLASH_AD_SOURCE_SELF.equals(splashAdCode)) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fl_container, SelfSplashFragment.newInstance())
                    .commitAllowingStateLoss();
//        } else if (SplashConfig.SPLASH_AD_SOURCE_SG.equals(splashAdCode)) {
//            if (BuildConfig.DEBUG) {
//                LogUtils.e("loadSplashAd  搜狗");
//            }
//            getSupportFragmentManager()
//                    .beginTransaction()
//                    .replace(R.id.fl_container, SGSplashFragment.newInstance(SGConfig.SPLASH_POS_ID))
//                    .commitAllowingStateLoss();
        } else {
            /**
             * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
             * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
             * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
             **/
            long alreadyDelayMills = System.currentTimeMillis() - mFetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
            long shouldDelayMills = alreadyDelayMills > MAX_SPLASH_LOAD_TIME ? 0 : MAX_SPLASH_LOAD_TIME
                    - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
            // 计算出还需要延时多久
            mHandler.postDelayed(mGoMainTask, shouldDelayMills);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    @Override
    public void goMain() {
        if (!isGoMain) {
            isGoMain = true;
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    @Override
    public void onLoadSuccess(AdInfo adInfo) {
        LogUtils.eTag("splash", "onLoadSuccess " + adInfo.toString());
        SplashConfig.saveLastSplashAd(adInfo);
        mHandler.removeCallbacks(mGoMainTask);
    }

    @Override
    public void onLoadFail(AdInfo adSourceCode, String errorMsg) {
        LogUtils.eTag("splash", "onLoadFail " + adSourceCode + " errorMsg " + errorMsg);
        //ToastUtils.showShort(adSourceCode.getType() + " 加载失败，" + errorMsg);
        SplashConfig.saveLastSplashAd(adSourceCode);
        SplashConfig.saveLastSplashOldAdCode(adSourceCode);

        if (SplashConfig.mPopAdOrderList != null && SplashConfig.mPopAdOrderList.size() > 2) {
            AdInfo adInfo = SplashConfig.getNextAdSource();
            loadSplashAd(adInfo);
        } else {
            String splashAdSource = SplashConfig.getSplashAdSource();
            loadSplashAd(splashAdSource);
        }
    }

    @Override
    public void onLoadSuccess(String adSourceCode) {
        LogUtils.eTag("splash", "onLoadSuccess " + adSourceCode);
        mHandler.removeCallbacks(mGoMainTask);
        SplashConfig.saveLastSplashAdCode(adSourceCode);
    }

    @Override
    public void onLoadFail(String adSourceCode, String errorMsg) {
        LogUtils.eTag("splash", "onLoadFail " + adSourceCode + " errorMsg " + errorMsg);
        String nextSplashAdCode = SplashConfig.getNextSplashAdCode(adSourceCode, mSplashAdOrderList, ++retryCount);
        if (BuildConfig.DEBUG) {
            //ToastUtils.showShort(adSourceCode + "加载失败 重试" + nextSplashAdCode);
        }
        loadSplashAd(nextSplashAdCode);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onChange(List<AdInfo> adInfos) {
        if (BuildConfig.DEBUG) {
            LogUtils.e("陈超 onChange  setAdList");
        }
        SplashConfig.setAdList(adInfos);
    }
}
